angular.module('app').constant('AppConstants', {
    ASC: 'asc',
    DESC: 'desc',
    filter: {
        STARTS_WITH: 2, // 前模糊
        ENDS_WITH: 4,   // 后模糊
        EXACT: 8,       // 精确匹配
        CONTAINS: 16,   // 全模糊
        GREATER_THAN: 32, // 大于
        GREATER_THAN_OR_EQUAL: 64,// 小于等于
        LESS_THAN: 128, // 大于
        LESS_THAN_OR_EQUAL: 256,// 大于等于
        NOT_EQUAL: 512, // 不等于
        SELECT: 'select',   // 精确匹配一般用与下拉框
        INPUT: 'input'      // 同 EXACT
    }
});

app.factory('TableFactory', ['httpWrapService', '$q', 'AppConstants', "$filter", function (httpWrapService, $q, AppConstants, $filter) {
    function Table(config) {
        var table = this;
        angular.extend(this, {
            url: '',
            pagination: true,
            data: [],
            params: [],
            pageSizes : [10,20,50],
            // 可以设置此属性修改默认页大小 defaultPageSize : 20,
            onFootable : function(footable){},
            outerParams : [],
            externalParams: {
                sort: [],
                filter: []
            },
            page: {
                pageSize: config.defaultPageSize || 20,
                pageNumber: 1
            }
        }, config);
    }

    Table.prototype = {
        /**
         * 装载表格数据
         */
        load: function () {
            var deferred = $q.defer();
            var table = this;
            // 读取查询参数
            // 读取分页、排序、过滤参数
            if (table.pagination) {
            	table.externalParams.pageSize = table.page.pageSize;
            	table.externalParams.pageNumber = table.page.currentPage;
            } else {
            	table.externalParams.pageSize = undefined;
            	table.externalParams.pageNumber = undefined;
            }
            table.externalParams.filter =[];
            for(var i = 0; i < table.params.length; i++) {
                var obj = angular.copy(table.params[i], {});
                if(obj['field']) {
                    if(obj['term']  || obj['term'] === false) {
                        if(!obj['type']) obj['type'] = AppConstants.filter.CONTAINS;
                        if(obj['dateFormat']){
                        	// 日期格式化
                        	obj['term'] = $filter('date')(obj['term'],obj['dateFormat']);
                        }
                        table.externalParams.filter.push(obj);
                    }
                }
            }
            var data = {
                externalParams: table.externalParams,
                outerParams : table.outerParams
            };
            httpWrapService.post(table.url, data).then(function (res) {
                // 处理后台分页
                if (table.pagination) {
                	table.page = res.data.page;
                	table.data = res.data.page.rows;
                    deferred.resolve(res.data.page);
                } else {
                	table.data = res.data.data;
                    deferred.resolve(res.data.data);
                }
            }, function (res) {
                deferred.reject(res);
            });
            return deferred.promise;
        },
        reset : function(){
        	var table = this;
        	// 参数重置
        	angular.forEach(table.params, function(data,index,array){
        		data.term = '';
    		});
        }
    }
    /**
     * 新建实例
     * @param config
     * @returns {Table}
     */
    Table.newInstance = function (config) {
        return new Table(config);
    }

    return {
        newInstance: function (config) {
            return Table.newInstance(config);
        }
    };
}]);

//footable 排序结果绑定
angular.module('app')
    .directive('appFootable', ['$compile', '$parse', 'uiLoad', 'JQ_CONFIG', 'TableFactory', function ($compile, $parse, uiLoad, JQ_CONFIG, TableFactory) {
        return {
            restrict: 'AC',
            link: function ($scope, element, attr) {
                uiLoad.load(JQ_CONFIG['footable']).then(function () {
                    var strTable = 'Table' + (attr.index ? attr.index : 1);
                    var table = $scope.$eval(strTable);
                    var footable = table.footable = $(element).footable();
                    table.onFootable(footable);
                    table.flushView = function(){
                        table.footable.trigger('footable_redraw');
                    }
                    if(table.pagination) {
                        $scope.$watchCollection(strTable + '.page.rows',function(newVal, oldVal){
                            if(newVal) {
                                table.flushView();
                            }
                        });
                    } else {
                        $scope.$watchCollection(strTable + '.data',function(newVal, oldVal){
                            if(newVal) {
                                table.flushView();
                            }
                        });
                    }
                    if (!!!attr.dataSort && table.pagination) {
                        footable.bind({
                            'footable_sorting': function (e) {
                                if (!table.externalParams.sort) table.externalParams.sort = [];
                                // 只支持一个列排序
                                var obj = {
                                    field: e.column.sort.name || e.column.name,
                                    direction: e.direction.toLowerCase(),
                                    priority: 1
                                }
                                
                                // 排序方式变化判断
                                if(table.originalSortName) {
                                	if(table.originalSortName == obj.field && table.originalSortDirection == obj.direction) {
                                		// 排序方式没有变化，不排序
                                		return false;
                                	}
                                }
                                // 保存上次排序
                                table.originalSortName = obj.field;
                                table.originalSortDirection = obj.direction;
                                
                                table.externalParams.sort[0] = obj;
                                
                                // 排序后到第一页
                                table.page.currentPage = 1;
                                
                                table.load().then(function () {
                                    table.flushView();
                                });
                                return true;
                            }
                        });
                    }
                });
            }
        };
    }]);

//分页结果绑定
angular.module('app')
    .directive('appPagination', ['$compile', function ($compile) {
        return {
            restrict: 'AC',
            templateUrl: 'app/pagination.tpl.html',
            scope: {
                pagination: '=appPagination'  // 传递table
            },
            link: function ($scope, element, attr) {
                if ($scope.pagination.load) {
                    $scope.query = function () {
                    	if($scope.pagination.page.currentPage)
                        $scope.pagination.load();
                    };
                    $scope.changePageSize = function () {
                        $scope.pagination.page.currentPage = 1;
                        $scope.pagination.load();
                    }
                }
            }
        };
    }]);


angular.module('app').run(["$templateCache", function ($templateCache) {
    $templateCache.put("app/pagination.tpl.html",
        "<div class=\"row padder-lg form-inline form-validation\" ng-if=\"pagination.page.total && pagination.pagination\">                                                                                                                                                                                                                                                                                                "
        + "<div class=\"input-group pull-left no-padder\">                                                                                                                                                                                                                                                                    "
        + "	<div class=\"input-group-addon\">本页{{ pagination.page.rows.length }}条,共{{ pagination.page.total }}条. 每页</div>                                                                                                                                                                                                                                                                                  "
        + "	<select class=\"form-control \" ng-change=\"changePageSize()\" ng-options=\"o for o in pagination.pageSizes\" ng-model=\"pagination.page.pageSize\" style=\"width:80px;\">                                                                                                                                                                                     "
        + "	</select>                                                                                                                                                                                                                                                                                                                            "
        + "	<div class=\"input-group-addon\">条,共{{ pagination.page.totalPage }}页.转到</div>                                                                                                                                                                                                                                                                                                           "
        + "	<input type=\"number\" class=\"form-control \" style=\"width:80px;\" ng-blur=\"query()\" ng-model=\"pagination.page.currentPage\" required ng-min=\"1\" ng-max=\"pagination.page.totalPage\">"
   		+"  <div class=\"input-group-addon\">页</div>                                                                                                                                           "
        + "</div>                                                                                                                                                                                                                                                                                                                                 "
        + "<uib-pagination class=\"pull-right\" total-items=\"pagination.page.total\" ng-change=\"query()\" ng-model=\"pagination.page.currentPage\" items-per-page=\"pagination.page.pageSize\" max-size=\"5\" class=\"m-t-none m-b\" boundary-links=\"true\" rotate=\"true\" previous-text=\"&lsaquo;\" next-text=\"&rsaquo;\" first-text=\"&laquo;\" last-text=\"&raquo;\"></uib-pagination>"
        + "</div>");
}]);
